package model;

import misc.Utils;

import java.io.IOException;

import static misc.Utils.DATA_FOLDER;

/**
 * Created with IntelliJ IDEA.
 * User: nuno-rafael-figueiredo
 * Date: 04-03-2014
 * Time: 17:38
 */
public abstract class Entity<Key, Item> extends Map<Key, Item> {

    protected final String name;
    protected final Class<Item[]> arrayClass;
    protected final Class<Item> itemClass;

    protected Entity(Class<Item[]> arrayClass, Class<Item> itemClass) {
        name = Utils.createName(getClass());

        this.arrayClass = arrayClass;
        this.itemClass = itemClass;

        load();
    }

    public final void load() {
        try {
            addAll(DATA_FOLDER.fromJson(getClass().getSimpleName(), arrayClass));
        } catch (Exception e) {
            parse();
            try {
                DATA_FOLDER.toJson(getClass().getSimpleName(), values());
            } catch (IOException e1) {
                throw new RuntimeException(e1);
            }
        }
    }

    protected final void addAll(Item[] items) {
        for (Item item : items)
            put(getKey(item), item);

        setChangedAndNotifyObservers();
    }

    public final void add(Item item) {
        put(getKey(item), item);

        setChangedAndNotifyObservers();
    }

    protected abstract Key getKey(Item item);

    protected abstract void parse();

    public final Item[] getArray() {
        try {
            return values().toArray(arrayClass.newInstance());
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public final String getName() {
        return name;
    }

    public final Class<Item> getItemClass() {
        return itemClass;
    }
}
